package com.wps.wdztv6.controller;

import com.wps.wdztv6.common.R;
import com.wps.wdztv6.entity.ThirdFile;
import com.wps.wdztv6.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Slf4j
@Controller
@RequestMapping("/download")
public class DownloadController {
    @Autowired
    FileService fileService;

    @RequestMapping("/file")
    public void downloadFile(@RequestParam("file_id") String fileId, @RequestParam Integer version, HttpServletResponse response) throws IOException {
        R<InputStream> fileR = fileService.downloadFile(fileId, version);
        R<ThirdFile> file = fileService.getFileByFileVersionId(fileService.generateVersionFileId(fileId,version));
        if (fileR.getResult() != 0) {
            response.setStatus(404);
            log.error("下载文件出错:{}",fileR.getMessage());
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(fileR.getMessage());
        } else {
            log.info("文件下载:{}",file);
            try {
                InputStream fis = new BufferedInputStream(fileR.getData());
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();

                // 清空response
                response.reset();
                // 设置response的Header
                response.setCharacterEncoding("UTF-8");
                //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
                //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
                // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getData().getName(), "UTF-8"));
                // 告知浏览器文件的大小
                response.addHeader("Content-Length", "" + file.getData().getSize());
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                outputStream.write(buffer);
                outputStream.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
